<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    img {
      width: 100px;
      height: 100px;
      border: 1px solid black;
      border-radius: 50%;
    }

    input {
      display: none;
    }
  </style>
</head>

<body>
  <img>
  <input type="file">

  <script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>
  <script>
    const img = document.querySelector('img')
    const input = document.querySelector('input')

    function uploadFile(file) {
      const formData = new FormData()
      formData.append('avatar', file)

      axios({
        url: 'http://ajax-api.itheima.net/api/file',
        method: 'POST',
        data: formData
      })
        .then(res => {
          if (res.status === 200) {
            img.src = res.data.data.url
          } else {
            console.log(res)
          }
        })
        .catch(err => {
          console.log(err)
        })
    }

    img.addEventListener('click', () => input.click())
    input.addEventListener('change', () => {
      if (input.files.length > 0) {
        uploadFile(input.files[0])
      }
    })
  </script>
</body>

</html>